/**
 * @description: 文件描述
 * @version: 0.0.1
 * @author: xxx
 * @Date: 2025-02-27 09:57:16
 */
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from '@/store/useState'
import { useRouter } from 'vue-router'
// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    const userStore = useStore()
    if (userStore.userInfo.token) {
      config.headers['Authorization'] = 'Bearer ' + userStore.userInfo.token
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  async response => {
    const res = response.data
    if (res.code !== 200) {
      ElMessage({
        message: res.errorMsg
          || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.errorMsg
        || 'Error'))
    } else {
      return res
    }
  },
  async error => {
    const { default: router } = await import('@/router')
    const res = error.response.data
    const userStore = useStore()
    // token过期
    if (res.code === 401) {
      ElMessageBox.confirm(res.errorMsg, {
        confirmButtonText: 'OK',
        type: 'warning'
      }).then(() => {
        userStore.deleteToken()
        router.push('/login')
        window.location.reload()
      })
    } else {
      ElMessage({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service